#!/bin/bash

set -e
BIN_DIR="/usr/local"
DOWNLOAD_DIR="$HOME/tools"
CONFIG_URL="https://gitee.com/michelalive/Deploy-repo/raw/master/runtime/containerd/config.toml"

# 检查命令是否成功
check_command() {
  if [ $? -ne 0 ]; then
    echo "错误: $1 失败。"
    exit 1
  fi
}

# 创建下载目录（如果不存在）
mkdir -p $DOWNLOAD_DIR && cd $DOWNLOAD_DIR || exit 1

# 下载 containerd 如果文件不存在
if [ ! -f containerd-1.7.14.tgz ]; then
   wget https://gczxdzmc-pro.obs.cn-north1.ctyun.cn/containerd-1.7.14.tgz
  check_command "下载 containerd-1.7.14.tgz"
  echo "containerd-1.7.14.tgz 下载成功"
fi

# 解压 containerd
tar -xzvf $DOWNLOAD_DIR/containerd-1.7.14.tgz
check_command "解压 containerd-1.7.14.tgz"
echo "containerd-1.7.14.tgz 解压成功"

cd  containerd || exit 1
tar -zxvf cri-containerd-cni-1.7.14-linux-amd64.tar.gz -C /

cat > /etc/cni/net.d/10-containerd-net.conflist << EOF
{
  "cniVersion": "1.0.0",
  "name": "containerd-net",
  "plugins": [
    {
      "type": "bridge",
      "bridge": "cni0",
      "isGateway": true,
      "ipMasq": true,
      "promiscMode": true,
      "ipam": {
        "type": "host-local",
        "ranges": [
          [{
            "subnet": "172.24.0.0/16"
          }]
        ],
        "routes": [
          { "dst": "0.0.0.0/0" }
        ]
      }
    },
    {
      "type": "portmap",
      "capabilities": {"portMappings": true}
    }
  ]
}
EOF

# 安装 runc
install -m 755 runc.amd64 $BIN_DIR/sbin/runc
check_command "安装 runc.amd64"
echo "runc.amd64 安装成功"

# 创建 crictl 配置文件
cat > /etc/crictl.yaml <<EOF
runtime-endpoint: "unix:///run/containerd/containerd.sock"
image-endpoint: "unix:///run/containerd/containerd.sock"
timeout: 0
debug: false
pull-image-on-create: false
disable-pull-on-run: false
EOF
check_command "创建 /etc/crictl.yaml"
echo "/etc/crictl.yaml 创建成功"

# 下载并解压 nerdctl
tar Cxzvf $BIN_DIR/bin  nerdctl-1.7.6-linux-amd64.tar.gz
check_command "解压 nerdctl-1.7.6-linux-amd64.tar.gz"
echo "nerdctl-1.7.6-linux-amd64.tar.gz 解压成功"

# 启动 containerd
systemctl enable containerd --now
mkdir -p /etc/containerd && wget -O /etc/containerd/config.toml $CONFIG_URL
systemctl daemon-reload && systemctl restart containerd

echo "设置成功完成。"
